// Copyright 2019 The Go Authors. All rights reserved.
// Use of this session code is governed by a BSD-style
// license that can be found in the LICENSE file.

package lsp

import (
	"context"
	"mi/internal/event"
	"mi/internal/lsp/protocol"
	"mi/internal/lsp/session"
	"mi/internal/xpath"
)

func (s *Server) definition(ctx context.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) {
	infos, err := s.session.GetDefinitionAtPosition(ctx, xpath.URI(params.TextDocument.URI), toUTF16Position(params.Position))
	if err != nil {
		event.Error(ctx, err.Error(), err)
		return nil, nil
	}
	return toProtocolLocations(infos), nil
}

func (s *Server) typeDefinition(ctx context.Context, params *protocol.TypeDefinitionParams) ([]protocol.Location, error) {
	infos, err := s.session.GetTypeDefinitionAtPosition(ctx, xpath.URI(params.TextDocument.URI), toUTF16Position(params.Position))
	if err != nil {
		event.Error(ctx, err.Error(), err)
		return nil, nil
	}
	return toProtocolLocations(infos), nil
}

func toProtocolLocations(infos []session.DefinitionInfo) []protocol.Location {
	var result []protocol.Location
	for _, info := range infos {
		result = append(result, protocol.Location{
			URI:   protocol.DocumentURI(info.Uri),
			Range: toProtocolRange(info.Range),
		})
	}

	return result
}